home *** CD-ROM | disk | FTP | other *** search
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <alloc.h>
- #include <ctype.h>
- char *test_str =
- "This is a string with a number \tof words in\nit to test"
- " the string word parsing function."
- /* Note that the string includes words separated by multiple spaces,
- as well as newlines and tabs. */
-
- int wordcount(char *str)
- {
- int count = 0;
- char *s;
- s=str;
- while(*s && isspace(*s))s++; //Skip leading spaces
- while(*s)
- {
- while(*s && !isspace(*s))
- s++; //Skip over the word
- while(*s && isspace(*s))
- s++; //Skip over all whitespace
- count++; //Increment count - Note it starts as 0 not 1
- }
- return(count);
- }
-
- void str_to_ptrarray(char *orgstr, char *ptrarray[])
- {
- int i=0;
- char *s;
- s=orgstr;
- while(*s && isspace(*s))
- s++; //Leading white space
- while(*s)
- {
- ptrarray[i]=s; //assign it
- i++;
- while(*s && !isspace(*s))
- s++; //skip over the word
- while(*s && isspace(*s))
- { //skip over the whitespace
- *s=0; //terminate the string
- s++;
- }
- }
- }
-
- int allocate_space(int nbr, char ***ptrarray, int size, char **string)
- {
- //Allocate the array pointers
- if( (*ptrarray= (char **)calloc(nbr,sizeof(char *))) ==NULL)
- return(0); //Allocate the string space
- if( (*string = (char *)calloc(size+1,sizeof(char))) == NULL)
- return(0);
- return(1);
- }
-
- void free_space(char ***ptrarray, char **string)
- {
- free(*ptrarray);
- free(*string);
- }
-
- void main(void)
- {
- char **ptrarray;
- char *strg;
- int wordcnt;
- int size;
- size = strlen(test_str);
- wordcnt=wordcount(test_str);
- allocate_space(wordcnt,&ptrarray,size,&strg);
- strcpy(strg,test_str);
- str_to_ptrarray(strg,ptrarray);
- for(size = 0;size < wordcnt;size++)
- printf("%s:n",ptrarray[size]);
- free_space(&ptrarray,&strg);
- }
-
-